using System.Collections.Generic;
using System.Linq;
using SharePoint.Security.ConfigAnalyzer.Engine.Base;
using SharePoint.Security.ConfigAnalyzer.Engine.Common;
using Microsoft.SharePoint.Administration;

namespace SharePoint.Security.ConfigAnalyzer.Engine.Rules.Others
{
    public class BlockedFileTypes : BaseRule
    {
        private readonly List<string> _fileExtensionsThatShouldBeBlocked = new List<string>
                                                                               {
                                                                                   "exe",
                                                                                   "dll"
                                                                               };

        public BlockedFileTypes()
        {
            RuleInfo = new RuleInfo
                           {
                               Title = "Blocked File Types",
                               Description = "Ensure malicious file types are blocked especially EXE and DLLs(Central Administration >blocked file types)",
                               ExpectedValue = string.Format(
                                   "{0} file types should be blocked.",
                                   string.Join(",", _fileExtensionsThatShouldBeBlocked.ToArray()))
                           };
        }

        #region Overrides of BaseRule

        public override void Validate()
        {
            SPAdministrationWebApplication caWebApp = ObjectHelper.SPAdministrationWeb;

            var blockedExtensions = caWebApp.BlockedFileExtensions;


            if (blockedExtensions == null || blockedExtensions.Count == 0)
            {
                CurrentValue = "No extensions are blocked";
                Status = Status.Fail;
            }
            else
            {
                var missingExtensions = _fileExtensionsThatShouldBeBlocked.Where(c => !blockedExtensions.Contains(c)).ToList();

                if (!missingExtensions.Any())
                {
                    CurrentValue = "Appropriate file types are blocked.";
                    Status = Status.Pass;
                }
                else
                {
                    CurrentValue = string.Format("Following types are not blocked: {0}", string.Join(",", missingExtensions.ToArray()));
                    Status = Status.Fail;
                }
            }
        }

        #endregion
    }
}